package com.husen.myapp.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.husen.myapp.service.WxCloudService;
import com.husen.myapp.util.ShopConstant;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

/**
 * Service Implementation for managing Shop.
 */
@Service
@Transactional
public class WxCloudServiceImpl  implements WxCloudService  {


	private final Logger log = LoggerFactory.getLogger(WxCloudServiceImpl.class);


    public WxCloudServiceImpl() {

    }


	@Override
	public Map uploadFile(String entityName,Long entityId,String column,byte[] data) {
		Map<String,Object> r = new HashMap<String,Object>();
		
		// 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(ShopConstant.QCLOUD_COS_SecretId, ShopConstant.QCLOUD_COS_SecretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(ShopConstant.QCLOUD_COS_Region));
         
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        try {
        	
        	File localFile = File.createTempFile("temp",null);
        	FileOutputStream fos = new FileOutputStream(localFile); 
        	BufferedOutputStream bos = new BufferedOutputStream(fos);
        	bos.write(data);
        	
        	String key = ShopConstant.QCLOUD_COS_SELL+"/"+entityName+"_"+entityId+"_"+column+ShopConstant.QCLOUD_COS_SELL_FIELD_TYPE;
        	PutObjectRequest putObjectRequest = new PutObjectRequest(ShopConstant.QCLOUD_COS_Bucket, key, localFile);
        	PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        	
        	r.put(ShopConstant.QCLOUD_COS_RETURN_URL, ShopConstant.QCLOUD_COS_DOWNLOAD_URL+key);
        	bos.close();
        	fos.close(); 
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }
        
		return r;
	}
     
  
}
